package licode.unisop.platform.application.service;

import licode.unisop.platform.application.gateway.SiPlatProviderManager;
import licode.unisop.provider.api.SiPlatformProvider;
import licode.unisop.provider.info.SiPlatIdFind;
import licode.unisop.provider.info.SiPlatformReg;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 实现默认的插件管理
 *
 * @author licode
 */
@Service
public class SiPlatProviderManagerDefault implements SiPlatProviderManager {
    private static final String DEF_NAME = "default";

    private final ConcurrentHashMap<String, SiPlatformProvider> platforms = new ConcurrentHashMap<>();

    @Resource
    private SiPlatformProvider siPlatformProvider;

    @PostConstruct
    public void init() {
        platforms.put(buildPlatKey(DEF_NAME, null), siPlatformProvider);
    }

    @Override
    public void registerPlatProvider(SiPlatformReg regInfo) {
        String key = buildPlatKey(regInfo.getPlatformId(), regInfo.getTenantId());
        if (platforms.containsKey(key)) {
            platforms.put(key, regInfo.getProvider());
        }
    }

    @Override
    public SiPlatformProvider findPlatProvider(SiPlatIdFind info) {
        String key = buildPlatKey(info.getPlatformId(), info.getTenantId());
        if (platforms.containsKey(key)) {
            return platforms.get(key);
        } else {
            return siPlatformProvider;
        }
    }

    private String buildPlatKey(String platId, String tenantId) {
        if (tenantId != null) {
            return platId + "_" + tenantId;
        } else {
            return platId + "_$DEF";
        }
    }
}
